package com.yonyou.train.util.index;

import com.yonyou.train.exception.ReleaseCourseException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class IndexUtil {
    public  static  String indexFolder = null;
    static {
        Properties properties = new Properties();
            indexFolder =Thread.currentThread().getContextClassLoader().getResource("").getPath()+"indexfolder";
    }
    //创建索引
    public static void createIndex(List<String> names){
        //从目标中读取文件内容并创建Document
        List<Document> docs = getDocuments(names);
        //创建分析器，standardAnalyzer标准分析器
        Analyzer standardAnalyzer = new StandardAnalyzer(Version.LUCENE_47);
        //指定索引存储目录
        Directory directory = null;
        try {
            directory = FSDirectory.open(new File(indexFolder));
        } catch (IOException e) {
            throw new ReleaseCourseException("服务器中没有该目录文件");
        }
        //创建索引操作配置对象
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_47, standardAnalyzer);
        //定义索引操作对象indexWriter
        IndexWriter indexWriter = null;
        try {
            indexWriter = new IndexWriter(directory, indexWriterConfig);
            indexWriter.deleteAll();
            //遍历目录下的文件生成的文档，调用indexWriter方法创建索引
            for (Document document : docs) {
                indexWriter.addDocument(document);
            }
            //索引操作流关闭
            indexWriter.close();
        } catch (IOException e) {
            throw new ReleaseCourseException("IO异常");
        }
    }
    public static List<Document> getDocuments(List<String> names) {
        List<Document> list = new ArrayList<Document>();
        for (String name : names) {
            Document document = new Document();
            Field nameStr = new StringField("name", name, Field.Store.YES);
            Field pinyinStr = new TextField("pinyin", Pinyin4jUtil.converterToFirstSpell(name) + " " + Pinyin4jUtil.converterToSpell(name), Field.Store.YES);
            document.add(nameStr);
            document.add(pinyinStr);
            list.add(document);
        }
        return list;
    }
}
